/**
 * Created by win7 on 2017/3/13.
 */
import React from "react";
import Relay from "react-relay";
import Confirm from "../../common/Confirm";
import DepartmentCreate from './DepartmentCreate';
import DepartmentEdit from './DepartmentEdit';
import {Checkbox} from 'antd';
import {Switch} from 'antd';
import Select from '../../common/Select'
import "./css/People.css";
import PeopleAdd from './PeopleAdd';
import DepartmentBatchEdit from './DepartmentBatchEdit';
import Muchforbid from './Muchforbid';
import DepartmentDelete from './DepartmentDelete';
import FindPersonnelListMutation from './mutation/FindPersonnelListMutation';
import DepartmentList from "./DepartmentList"
import PeopleDetail from"./PeopleDetail"
import GetDepartmentsMutation from "./mutation/GetDepartmentsMutation"
import CreateOrUpdateDepartmentMutation from './mutation/CreateOrUpdateDepartmentMutation'
import DeleteDepartmentMutation from './mutation/DeleteDepartmentMutation'
import GetRolesMutation from "./mutation/GetRolesMutation"
import ReactKey from "../../util/ReactKey"
import PeopleEdit from "./PeopleEdit"

import {Button} from 'fly';
import classnames from 'classnames';
import ReactDOM from 'react-dom';


//asd
/*人员管理*/
export default class People extends React.PureComponent{
    constructor(props) {
        super(props);
        this.state = {
            Department: [],
            leftTabstate: false,
            defaultValue: '',
            allWorker: false,
            bottomShadow:false,  //是否显示menuBottom下的阴影效果
        }
        this.Style = {}
        this.Department = [];
        this.partid = ''
        this.deparmentc = {}
        this.selectArr = [
            {text: "启用员工", value: "启用员工"},
            {text: "停用员工", value: "停用员工"}
        ]
        this.peopleData = [];
        this.defaultValue = '';
        this.rid = '';
        this.status = 1;
        this.choseuidlist = []
        this.index = 0
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.permissionId = sessionStorage.getItem('permissionId');
        this.findAll = false;

        this.handleMenuScroll = this.handleMenuScroll.bind(this);
    }

    componentWillMount() {
        this.getDepartments(10, 1);
        // this.getAllPerson();
        this.partid = 0;
        this.Style = {
            main: {
                width: '100%',
                height:"inherit",
                overflow:"hidden"
            },
            section: {
                backgroundColor: 'white',
                width: 165,
                height: '100%',
                float: 'left',
                borderLeft: '1px solid #efefef',
                borderRight: '1px solid #efefef',
                borderBottom: '1px solid #efefef',
                textAlign: 'center'
            },
            sectioncontext: {
                backgroundColor: 'white',
                position:"relative",
                height: '100%',
                border: '1px solid #efefef',
                left:10
            },
            sectointitle: {
                display: 'block',
                width: '100%',
                height: '46px',
                borderBottom: '1px solid #ededed',
                textAlign: "center",
                lineHeight: "46px"
            },
            new_Department: {
                color: '#666',
                marginTop: '12px',
                fontSize: '12px',
                border: '1px solid #ededed',
                display: 'inline-block',
                width: 66,
                height: 21,
                lineHeight: '21px',
                textAlign: 'center',
                cursor: 'pointer',
                marginLeft: '10px'
            },
            editor_Department: {
                color: '#666',
                display: 'inline-block',
                width: '66px',
                height: '21px',
                fontSize: '12px',
                cursor: 'pointer',
                textAlign: 'center',
                border: '1px solid #ededed',
                float: 'right',
                marginTop: '12px',
                marginRight: '10px'

            },
            operation_people: {
                height: 50
            },
            add_people: {
                width: '96px',
                backgroundColor: "#36b3b3",
                color: 'white',
                fontSize: '14px',
                marginTop: '10px',
                marginBottom: '20px',
                height: '26px',
                borderRadius: 5,
            },
            public_lot: {
                padding: '0 10px',
                width: '102px',
                fontSize: '14px',
                color: 'white',
                height: '26px',
                backgroundColor: '#ffd430'
            },
            public_lot1: {
                padding: '0 10px',
                width: '102px',
                fontSize: '14px',
                color: 'white',
                backgroundColor: '#69ca9c',
                height: '26px'
            },
            public_lot2: {
                padding: '0 10px',
                width: '102px',
                fontSize: '14px',
                color: 'white',
                backgroundColor: '#eb4549',
                height: '26px'
            },
            public_lot3: {
                paddingLeft: '10px',
                width: '90px',
                fontSize: '14px',
                color: 'white',
                backgroundColor: '#ffd430',
                height: '26px'
            }
        }
    }

    getDepartments(pageSize, pageNum) {
        this.Department = [];
        Relay.Store.commitUpdate(
            new GetDepartmentsMutation({
                enterprizeId: this.enterpriseId
            }),
            {
                onFailure: () => {
                    // console.warn('erere')
                },
                onSuccess: (response) => {
                    let errorcode = response.getDepartments.getDepartments.errorCode
                    if (errorcode == 0) {
                        let departments = response.getDepartments.getDepartments.departmentModels
                        // var item = {name: '全部员工', pkId: {enid: this.enterpriseId}};
                        // this.Department.push(item);
                        departments.map((context, index)=> {
                            this.Department.push(context);
                            this.deparmentc[context.pkId.rid] = context.name
                        });
                        if (departments.length > 0) {
                            this.rid = this.Department[0].pkId.rid;
                            this.setState({
                                Department: this.Department
                            }, ()=> {
                                // this.onchose(this.Department[0].pkId.rid, 0);
                                this.getAllPerson();
                            });
                        } else {
                            this.setState({
                                Department: this.Department
                            }, ()=> {
                                this.getAllPerson();
                            });

                        }

                    }
                }
            }
        )
    }

    onchose(depid, id) {
        this.findAll = false;
        this.choseuidlist = [];
        this.refs.peopledetail.initpagenum();
        if (id != -1) {
            this.refs[id + 'add'].onchose();
        }
        this.Department.map((context, index)=> {
            if (context.pkId.rid != depid) {
                this.refs[index + 'add'].unchose();
            }
        });
        this.rid = depid;
        this.partid = depid;
        this.index = id;
        this.serchpeople(10, 1);
        this.setState({
            defaultValue: this.rid,
            allWorker: false
        });
    }

    //asdasd
    serchpeople(size, num, value) {
        this.refs.peopledetail.refs.allcheck.unchose();
        var depId = this.rid;
        var peopleState = this.status;
        if (this.findAll == true) {
            depId = null;
        }

        Relay.Store.commitUpdate(
            new FindPersonnelListMutation({
                enterpriseId: this.enterpriseId,
                rid: depId,
                status: peopleState,
                pageSize:10,
                pageNum:num,
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorcode = response.findPersonnelList.findPersonnelList.errorCode;
                    if (errorcode == 0) {
                        let userModelList = response.findPersonnelList.findPersonnelList.userModelList;
                        let totalresult = response.findPersonnelList.findPersonnelList.totalResult;
                        this.totalresult = totalresult;
                        if (userModelList != null && userModelList.length != 0) {
                            this.refs.peopledetail.setState({
                                peopleData: userModelList,
                                totalresult: totalresult,
                            });
                            if (value) {
                                this.refs.peopledetail.refs.pagination.setState({
                                    text: 1
                                });
                            }
                        } else {
                            this.refs.peopledetail.setState({
                                peopleData: [],
                                totalresult: 0,
                            });
                            this.refs.peopledetail.refs.pagination.setState({
                                text: ''
                            });
                        }
                        this.choseuidlist = [];
                        this.refs.peopledetail.uidlist = [];
                    }
                }
            }
        )
    }

    addDepartmenlist() {
        this.datasize = this.state.Department.length;
        return this.state.Department.map((context, index)=> {
            return (
                <DepartmentList key={index + '-'} context={context.name} ref={index + 'add'}
                               onchose={this.onchose.bind(this, context.pkId.rid, index)} index={index}/>
            );
        });
    }
    //新建部门弹窗出现
    addpart() {
        this.refs.creatpart.setState({
            visible: true,
            depName: '',
            description: ''
        },()=>{
            this.refs.creatpart.refs.departmentName.state.text="";
            this.refs.creatpart.refs.departmentdescription.state.text="";
        });
    }

    //编辑部门弹窗出现
    editorpart() {
        if (this.findAll == true) {
            return;
        }
        this.refs.editpart.setState({
            visible: true,
        }, ()=> {
            let part = this.Department[this.index]
            this.refs.editpart.setname(part.name, part.description);
        })
    }

    //编辑部门
    fixpartment(name, description) {
        this.refs.editpart.setState({
            visible: false
        });
        let department = this.Department[this.index];
        let rid = department.pkId.rid;
        Relay.Store.commitUpdate(
            new CreateOrUpdateDepartmentMutation({
                enterprizeId: this.enterpriseId,
                name: name,
                description: description || '',
                rid: rid
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {

                    let errorCode = response.createOrUpdateDepartment.createOrUpdateDepartment.errorCode

                    if (errorCode == 0) {
                        let department = response.createOrUpdateDepartment.createOrUpdateDepartment.department
                        this.Department.splice(this.index, 1, department);
                        this.setState({
                            Department: this.Department
                        });
                        this.onchose(rid, this.index);
                        // this.getAllPerson();
                    }else if (errorCode == "100002") {
                        this.refs.editpart.setState({
                            visible: true,
                        });
                        this.refs.editpart.setState({
                            depName: "部门名称已存在"
                        });
                        return;
                    }
                }
            }
        )
    }


    //批量修改部门弹窗出现
    modifypart() {
        let department = [{text: "请选择部门", value: "0"}];
        let departmentforchoose = [];
        this.Department.map((item, index)=> {
            // if (item.name != '全部员工') {
            department.push({text: item.name, value: item.pkId.rid});
            departmentforchoose.push(item.pkId.rid);
            // }
        });
        let departmentId = this.partid;
        if (this.findAll == true) {
            departmentId = 0;
        }

        this.refs.modifypart.setState({
            visible: true,
            uidlist: this.choseuidlist,
            departname: department,
            partid: departmentId,
            departmentforchoose: departmentforchoose
        });
    }

    //批量修改工作弹窗出现
    modifyjob() {
        this.refs.modifyjob.setState({
            visible: true
        })
    }

    //新建部门的功能的实现
    addDepartment(name, description) {

        if (!this.refs.creatpart.validate('depName')) {
            return
        }
        if (!this.refs.creatpart.validate('departmentdescription')) {
            return
        }
        Relay.Store.commitUpdate(
            new CreateOrUpdateDepartmentMutation({
                enterprizeId: this.enterpriseId,
                name: name,
                description: description || '',
                depId: this.partid
            }),
            {
                onFailure: (response) => {
                },

                onSuccess: (response) => {

                    let errorCode = response.createOrUpdateDepartment.createOrUpdateDepartment.errorCode

                    if (errorCode == "100002") {
                        this.refs.creatpart.setState({
                            depName: "部门名称已存在"
                        });
                        this.refs.creatpart.setState({
                            visible: true,
                        });
                        return;
                    }

                    this.refs.creatpart.setState({
                        visible: false,
                    });

                    if (errorCode == 0) {
                        let department = response.createOrUpdateDepartment.createOrUpdateDepartment.department
                        this.Department.splice(0, 0, department)
                        this.setState({
                            Department: this.Department,
                            p:new Date().getTime()
                        }, ()=> {
                            // this.onchose(this.Department[0].pkId.rid, 0);
                            this.getAllPerson();
                        });
                    } else {

                    }

                }
            }
        )
    }

    //添加员工弹窗出现
    addpeople() {
        let department = [{text: "请选择部门", value: "0"}];
        let departmentforchoose = [];
        this.Department.map((item, index)=> {
            // if (item.name != '全部员工') {
            department.push({text: item.name, value: item.pkId.rid});
            departmentforchoose.push(item.pkId.rid);
            // }
        });
        let departmentId = this.partid;
        if (this.findAll == true) {
            departmentId = 0;
        }
        this.refs.addstaff.setState({
            visible: true,
            departname: department,
            enabled:false,
            partid: departmentId,
            departmentforchoose: departmentforchoose
        })
    }

    functest() {
        this.refs.deletepart.setState({
            visible: true
        })
    }

    //删除部门
    deletpartcallback() {
        let department = this.Department[this.index];
        let rid = department.pkId.rid;
        let enid = department.pkId.enid
        Relay.Store.commitUpdate(
            new DeleteDepartmentMutation({
                enterprizeId: this.enterpriseId,
                rid: rid,
                enid: enid.toString(),
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.deleteDepartment.deleteDepartment.errorCode
                    if (errorCode == 0) {
                        this.Department.splice(this.partid, 1)
                        this.refs.editpart.setState({
                            visible: false
                        });
                        this.getDepartments();
                        // this.getAllPerson();
                    }
                }
            }
        )

    }

    onselectchose(value) {
        if (value == '停用员工') {
            this.status = 0
        } else {
            this.status = 1
        }
        this.serchpeople(10, 1, value);
    }

    getchosepeople(uidlist) {
        this.choseuidlist = uidlist
    }

    //编辑员工
    editstaffinfo(phone, name, uid, roleId, email, depId) {
        let role = [{text: "请选择职务", value: "0"}];
        let corresponding = {};
        Relay.Store.commitUpdate(
            new GetRolesMutation({
                enid: this.enterpriseId,
                isAll: 'zhaobin'
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorcode = response.getRoles.getRoles.errorCode;
                    if (errorcode == 0) {
                        let role = [{text: "请选择职务", value: "0"}];
                        let roles = response.getRoles.getRoles.roles;
                        roles.map((context, index)=> {

                            let name = context.name;
                            let roid = context.roleid.rid;
                            let enid = context.roleid.enid;
                            role.push({"text": name, value: roid})
                        });

                        let department = [{text: "请选择部门", value: "0"}];
                        let departmentforchoose = [];
                        this.Department.map((item, index)=> {
                            department.push({text: item.name, value: item.pkId.rid});
                            departmentforchoose.push(item.pkId.rid);
                        });
                        let departmentId = depId;
                        if (depId == null) {
                            departmentId = 0;
                        }

                        this.refs.editstaffinf.setState({
                            visible: true,
                            phone: phone,
                            name: name,
                            uid: uid,
                            depId: departmentId,
                            role: role,
                            roleId: roleId,
                            defaultValue: this.partid,
                            index: this.index,
                            departname: department,
                            partid: this.index,
                            departmentforchoose: departmentforchoose,
                            ratepayer:""
                        }, ()=> {
                            this.refs.editstaffinf.refs.name.setState({
                                text: name
                            });
                            this.refs.editstaffinf.refs.phone.setState({
                                text: phone
                            });
                            if (!email) {
                                email = ''
                            }
                            this.refs.editstaffinf.refs.email.setState({
                                text: email
                            });
                            this.refs.editstaffinf.refs.password.setState({
                                text: '********'
                            });
                        });
                    }
                }
            }
        )
    }

    getAllPerson(){
        let num = this.state.Department;
        for (let i in num) {
            try{
                this.refs[i + 'add'].unchose();
            }catch (e){}
        }
        this.findAll = true;
        this.serchpeople(10, 1);
        this.setState({
            allWorker: true
        })
    }

    onSure(size, num) {
        this.getDepartments(size, num)
    }

    handleMenuScroll(e){
        if(e.target.scrollTop > 0 && !this.state.bottomShadow){
            this.setState({
                bottomShadow:true
            })
        }else if(e.target.scrollTop === 0){
            this.setState({
                bottomShadow:false
            })
        }
    }

    render() {
        const {bottomShadow} = this.state;
        return (
            <div style={this.Style.main} className="clearfix">

                <div className="people_section--menu___left" style={this.Style.section} ref={'tab'}>
                    <div className={classnames({"people_menu--title":true,"people_shadowBottom":bottomShadow})}>
                        <span className="new_Department" onClick={this.addpart.bind(this)}><i></i> 新建</span>
                        <span className="editor_Department" onClick={this.editorpart.bind(this)}><i></i> 编辑</span>
                    </div>
                    <div className="people_section--menu___bottom_container" onScroll={this.handleMenuScroll}>
                        <div className="people_section--menu___bottom">
                            {/*allWorker*/}
                            <div className={this.state.allWorker ? "getAllPerson active" : "getAllPerson" }
                                 onClick={this.getAllPerson.bind(this)}>
                                全部员工
                            </div>
                            {
                                this.addDepartmenlist()
                            }
                        </div>
                    </div>
                </div>

                <div className="people_table--box">
                    <div style={this.Style.operation_people}>
                        {/*<Confirm tcontext={''} style={this.Style.add_people} touch={}/>*/}
                        <Button onClick={this.addpeople.bind(this)} size="small" className="people_addStaff"> 添加员工 </Button>
                        {/*<Select></Select>*/}
                        <ul className="lot_position">
                            <li>
                                <Button onClick={this.modifypart.bind(this)} type="blank" size="small"> 批量修改部门 </Button>
                            </li>

                            <li className="people_off--select">
                                <Select oArr={this.selectArr}
                                        style={this.Style.public_lot3}
                                        ref={'selectvalue'}
                                        onselectchose={this.onselectchose.bind(this)}
                                />
                            </li>
                        </ul>
                    </div>
                    <PeopleDetail peopleDetailData={this.peopleData} ref={'peopledetail'}
                                  serchpeople={this.serchpeople.bind(this)}
                                  getchosepeople={this.getchosepeople.bind(this)}
                                  editstaffinfo={this.editstaffinfo.bind(this)}
                    />
                </div>

                {/*弹窗*/}
                <DepartmentCreate ref={'creatpart'} getAllPerson={this.getAllPerson.bind(this)}
                            addDepartment={this.addDepartment.bind(this)} findAll={this.findAll} key={ReactKey.key}/>
                <DepartmentEdit ref={'editpart'} getAllPerson={this.getAllPerson.bind(this)} deparmentc={this.deparmentc}
                          functest={this.functest.bind(this)} findAll={this.findAll}
                          fixpartment={this.fixpartment.bind(this)} key={ReactKey.key}/>
                <PeopleAdd ref={'addstaff'} getAllPerson={this.getAllPerson.bind(this)} deparmentc={this.deparmentc}
                          onchose={this.onchose.bind(this)} findAll={this.findAll} key={ReactKey.key}
                          defaultValue={this.state.defaultValue}/>
                <DepartmentBatchEdit ref={'modifypart'} getAllPerson={this.getAllPerson.bind(this)} key={ReactKey.key}
                                choseuidlist={this.choseuidlist} findAll={this.findAll}
                                defaultValue={this.state.defaultValue} onchose={this.onchose.bind(this)}
                                deparmentc={this.deparmentc}/>
                <DepartmentDelete ref={'deletepart'} getAllPerson={this.getAllPerson.bind(this)}
                            deletpartcallback={this.deletpartcallback.bind(this)} findAll={this.findAll}
                            partid={this.partid} key={ReactKey.key}/>
                <PeopleEdit ref={'editstaffinf'} onchose={this.onchose.bind(this)}
                               getAllPerson={this.getAllPerson.bind(this)} key={ReactKey.key}
                               defaultValue={this.state.defaultValue} findAll={this.findAll}/>
            </div>
        )
    }
}